import userBaseInfo from '../../../../stores/userBaseInfo';
import { getBMI , getHeartRate , getNewestBPL , getDisease , getPMH , getPH , getFH } from '../../../../utils/api/medicalCondition'

// pages/home/home-nav/medical-condition/medical-condition.ts
Component({

  /**
   * 组件的属性列表
   */
  properties: {

  },

  /**
   * 组件的初始数据
   */
  data: {
    userInfo: <PatientBaseEntity>{
      patientUid: '',
      wxUid: '',
      physicalStrength: '',
    },
    user: {
      PCS: '0分（优秀）',
      height: 0,
      weight: 0,
      SBP: 0,
      DBP: 0,
      HR: 0,
      diseaseInfo: [{
        name: '请添加您的疾病信息',
        year: 0,
        month: 0,
      }],
      pastMedicalHistory: '未找到该患者的AI预问诊表单',
      personalHistory: '未找到预问诊信息',
      familyHistory: '未找到家族史记录'
    }
  },


  /**
   * 组件的方法列表
   */
  methods: {
    updatePCS() {
      // console.log('获取到的PCS是', this.data.userInfo.physicalStrength);
      if (this.data.userInfo.physicalStrength === null) {
        this.setData({
          'user.PCS': '暂无数据，请添加'
        })
      }
      if (this.data.userInfo.physicalStrength === 0) {
        this.setData({
          'user.PCS': '0分（优秀）'
        });
        // console.log('现在的PCS是', this.data.user.PCS);
      }
      if (this.data.userInfo.physicalStrength === 1) {
        this.setData({
          'user.PCS': '1分（良好）'
        });
        // console.log('现在的PCS是', this.data.user.PCS);
      }
      if (this.data.userInfo.physicalStrength === 2) {
        this.setData({
          'user.PCS': '2分（一般）'
        });
        // console.log('现在的PCS是', this.data.user.PCS);
      }
      if (this.data.userInfo.physicalStrength === 3) {
        this.setData({
          'user.PCS': '3分（较差）'
        });
        // console.log('现在的PCS是', this.data.user.PCS);
      }
      if (this.data.userInfo.physicalStrength === 4) {
        this.setData({
          'user.PCS': '4分（极差）'
        });
        // console.log('现在的PCS是', this.data.user.PCS);
      }
    },
    updateBMI() {
      let patientUid = userBaseInfo.data.patientUid as string;
      // console.log('获取的patientUId', patientUid);
      getBMI(patientUid).then((res: any) => {
        // console.log('身高体重请求成功', res);
        if (res.code === 0 && Array.isArray(res.data) && res.data.length > 0) {
          // 按日期排序，找到最新的一条记录
          const latestRecord = res.data.sort((a: any, b: any) =>
            new Date(b.bmimeasurementDate).getTime() - new Date(a.bmimeasurementDate).getTime()
          )[0];
          this.setData({
            'user.height': latestRecord.height,
            'user.weight': latestRecord.weight,
          });
          // console.log('现在的身高是', this.data.user.height, '现在的体重是', this.data.user.weight);
        } else {
          console.log('没有找到有效的身高体重数据');
        }
      }).catch((err: any) => {
        console.log('身高体重请求失败', err);
      })
    },
    updateBPL() {
      let patientUid = userBaseInfo.data.patientUid as string;
      getNewestBPL(patientUid).then((res: any) => {
        // console.log('基础血压心率请求成功', res);
        this.setData({
          'user.SBP': res.data['收缩压'],
          'user.DBP': res.data['舒张压'],
          'user.currentLevel': res.data['风险评估'],
        })
      }).catch((err: any) => {
        console.log('基础血压心率请求失败', err);
      })
    },
    updateHR() {
      let patientUid = userBaseInfo.data.patientUid as string;
      getHeartRate(patientUid).then((res: any) => {
        // console.log('最新的心率是', res);
        this.setData({
          'user.HR': res.data['心率'],
        })
      }).catch((err: any) => {
        console.log('心率请求失败', err);
      })
    },
    updateDisease() {
      let patientUid = userBaseInfo.data.patientUid as string;
      getDisease(patientUid).then((res: any) => {
        if (res.code === 0 && res.data.length!==0) {
          this.data.user.diseaseInfo = res.data.map((item: any) => ({
            name: item["disease_name: "],
            year: item["year: "],
            month: item["month: "],
          }));
          this.setData({
            'user.diseaseInfo':this.data.user.diseaseInfo,
          })
        } else {
          console.error("Failed to update disease information", res.msg);
        }
      }).catch((err: any) => {
        console.error("API call failed", err);
      });
    },
    updateHistory() {
      let patientUid = userBaseInfo.data.patientUid as string;
      getPMH(patientUid).then((res: any) => {
        this.setData({
          'user.pastMedicalHistory': res,
        })
      }).catch((err: any) => {
        console.log('获取预问诊既往史失败', err);
      })
      getPH(patientUid).then((res: any) => {
        this.setData({
          'user.personalHistory': res,
        })
      }).catch((err: any) => {
        console.log('获取预问诊个人史失败', err);
      })
      getFH(patientUid).then((res: any) => {
        this.setData({
          'user.familyHistory': res,
        })
      }).catch((err: any) => {
        console.log('获取预问诊家族史失败', err);
      })
    },
    updateUserInfo(userInfo: PatientBaseEntity) {
      var that = this
      this.data.userInfo = userInfo;
      this.setData({
        userInfo: userInfo,
      })
      // console.log('condition获取的userInfo', this.data.userInfo);
      that.updatePCS();
      that.updateBMI();
      that.updateHR();
      that.updateBPL();
      that.updateDisease();
      that.updateHistory();
      // TODO: 自己添加更新echart等等数据逻辑
    },
  },

  pageLifetimes: {
    show: function () {
      this.updateUserInfo(this.data.userInfo);
    }
  }
})